--[[
    @desc 界面管理器
    	  1 其他层的界面打开会隐藏main层的界面
    	  2 打开A界面再打开B界面，A界面会隐藏，再打开C界面，B界面会隐藏，达到下一界面打开后会隐藏之前的界面，下一界面关闭后会显示之前的界面
    @author zch
    @data:2022-04-19 9:42:00
]]

local _stack = require "Common/stack"

LuaViewManager = LuaViewManager or BaseClass(EventDispatcher)
local LuaViewManager = LuaViewManager

function LuaViewManager:__init()
	-- LuaViewManager.Instance = self
	-- self.view_queue_ctrl = Array.New()
	-- self.view_queue_ctrl = {}
	-- self.view_id = 0
	self.view_stack = _stack.New()
end

function LuaViewManager:GetInstance()
	if LuaViewManager.Instance == nil then
		LuaViewManager.Instance = LuaViewManager.New()
	end
	return LuaViewManager.Instance
end

function LuaViewManager:LoadView(abName, pfName, layerName, call_back)
	panelMgr:CreateView(abName, pfName, layerName, call_back)
end

function LuaViewManager:LoadItem(abName, pfName, parent, call_back)
	panelMgr:CreateItem(abName, pfName, parent, call_back)
end

function LuaViewManager:OpenView(target)
	-- if target.append_queue_ctrl and self.view_queue_ctrl[target] == nil then
	-- 	for view, _ in pairs(self.view_queue_ctrl) do
	-- 		view:Hide()
	-- 	end
	-- 	self.view_id = self.view_id + 1
	-- 	self.view_queue_ctrl[target] = self.view_id
	-- end
	if target.append_queue_ctrl and not self.view_stack:Contains(target) then
		local view = self.view_stack:Peek()
		if view then
			view:Hide()
		end
		self.view_stack:Push(target)
	end
end

function LuaViewManager:CloseView(target)
	-- if target.append_queue_ctrl then
	-- 	self.view_queue_ctrl[target] = nil
	-- 	local max_id = 0
	-- 	local max_view = nil
	-- 	for view, id in pairs(self.view_queue_ctrl) do
	-- 		if id > max_id then
	-- 			max_id = id
	-- 			max_view = view
	-- 		end
	-- 	end
	-- 	if max_view then
	-- 		max_view:CancelHide()
	-- 	end
	-- end
	if target.append_queue_ctrl then
		local view = self.view_stack:Peek()
		if view and view == target then
			self.view_stack:Pop()
			local last_view = self.view_stack:Peek()
			if last_view then
				last_view:CancelHide()
			end
		end
	end
end

function LuaViewManager:DestroyView(gameObject)
	destroy(gameObject)
end

function LuaViewManager:DestroyItem(gameObject)
	destroy(gameObject)
end